package com.hfzy.ihk.web.oauth.server.conf;



import com.hfzy.ihk.web.oauth.server.filter.MyUsernamePasswordAuthenticationFilter;
import com.hfzy.ihk.web.oauth.server.handler.LoginSuccessHandler;
import com.hfzy.ihk.web.oauth.server.handler.MyLogoutSuccessHandler;
import com.hfzy.ihk.web.oauth.server.support.security.UserDetailsServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.security.oauth2.client.EnableOAuth2Sso;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.event.EventListener;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
import org.springframework.security.authentication.event.InteractiveAuthenticationSuccessEvent;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.authentication.*;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;

/**
 * Created by chenzesen on 2019/1/2.
 * <p>
 * 授权中心权限配置类，请谨慎修改
 *
 * @author wws
 */
@Configuration
@Order(1)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired(required = false)
    MyLogoutSuccessHandler myLogoutSuccessHandler;


//
//    @Autowired(required = false)
//    CustomerSecurityFilter customerSecurityFilter;
    /**
     * 忽略静态文件
     */
    @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring().antMatchers("/frame/**", "/images/**", "/css/**", "/js/**", "/video/**", "/**/favicon.ico",
                "/captcha/getCaptcha", "/404", "/error","/exit/**","**/logout/**");
    }

    @Bean
    @Override // share AuthenticationManager for web and oauth
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

    @Bean
    public LoginSuccessHandler loginSuccessHandler() {
        return new LoginSuccessHandler();
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.requestMatchers()
                .and()
                .addFilterAt(myUsernamePasswordAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class)
                .authorizeRequests()
                .antMatchers("/oauth/**","/exit/**").permitAll()  //不拦截 oauth 开放的资源 可以用于客户端模式验证,注销功能也不用
                .anyRequest().authenticated().and()
                .cors().disable()
//                .cors().configurationSource(configurationSource()) //打开login页面的跨域请求
//                .and()
                .logout().logoutSuccessUrl("/login")
                .permitAll().and()  //s
                //测试登出 end
                .formLogin().loginPage("/login")// 自定义登录页面
                .permitAll()
                .and()
                .headers().frameOptions().disable() //这里比较重要，不然这在客户端session过期以后因为iframe跨域问题会跳不回验证页面
                .and()
                .csrf().disable().httpBasic().disable();//这个很重要，不然开启不了客户端模式



    }

    /**
     * 放开跨域用于iframe 页面过期
     * @return
     */
    @Bean
    public CorsConfigurationSource configurationSource() {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        CorsConfiguration config = new CorsConfiguration();
        config.addAllowedOrigin("*");
        config.setAllowCredentials(true);
        config.addAllowedHeader("X-Requested-With");
        config.addAllowedHeader("Content-Type");
        config.addAllowedMethod(HttpMethod.GET);
        config.addAllowedMethod(HttpMethod.POST);
        source.registerCorsConfiguration("/login", config);
        return source;
    }



    /**
     * 自定义验证码拦截器
     * @return
     * @throws Exception
     */
    @Bean
    public MyUsernamePasswordAuthenticationFilter myUsernamePasswordAuthenticationFilter() throws Exception {

        MyUsernamePasswordAuthenticationFilter myFilter = new MyUsernamePasswordAuthenticationFilter();
        myFilter.setAuthenticationManager(authenticationManagerBean());
        myFilter.setAuthenticationFailureHandler(authenticationFailureHandler());
        myFilter.setAuthenticationSuccessHandler(loginSuccessHandler());
        return myFilter;

    }

    @Bean
    public DaoAuthenticationProvider authenticationProvider() {
        DaoAuthenticationProvider authenticationProvider = new DaoAuthenticationProvider();
        authenticationProvider.setHideUserNotFoundExceptions(false);
        authenticationProvider.setUserDetailsService(userDetailsServiceImpl());
        return authenticationProvider;
    }


    /**
     * 自定义验证方法
     * @return
     */
    @Bean
    public UserDetailsServiceImpl userDetailsServiceImpl() {
        return new UserDetailsServiceImpl();
    }


    /**
     * 自定义登录验证
     * @param auth
     * @throws Exception
     */
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {

        auth.userDetailsService(userDetailsServiceImpl()).passwordEncoder(passwordEncoder());


    }



    /**
     * 配置登录失败处理接口，失败以后跳回/login 通过拦截异常判断失败原因
     * @return
     */
    @Bean
    public AuthenticationFailureHandler authenticationFailureHandler() {
        return new SimpleUrlAuthenticationFailureHandler("/login");
    }


    /**
     * 密码加密工具
     * @return
     */
    @Bean
    public BCryptPasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }


    /**
     * 监听登录成功监听器，
     * @param event
     */
    @EventListener
    public void authSuccessListener(InteractiveAuthenticationSuccessEvent event) {
        System.out.println("哎呦喂，登录成功了");


    }



}
